﻿CREATE FUNCTION PaymentsApart(
	@DateStart datetime,
	@DateEnd datetime,
	@FreqPerYear tinyint
)RETURNS @T TABLE (Periods int,OddDays int) WITH SCHEMABINDING
BEGIN

SELECT 	@DateStart = dbo.Today(@DateStart) ,	@DateEnd = dbo.Today(@DateEnd)

DECLARE @FNP int/*No Periods */
IF @FreqPerYear IN (12,24) BEGIN
	SET @FNP = dbo.MonthsApart(@DateStart,@DateEnd)
	IF @FreqPerYear = 24 SET @FNP = @FNP * 2 + CASE WHEN DATEDIFF(dd,DATEADD(mm,@FNP,@DateStart),@DateEnd)> 15 THEN 1 ELSE 0 END
END ELSE BEGIN
	SET @FNP = 
			CASE @FreqPerYear
				 WHEN 26 THEN DATEDIFF(dd,@DateStart,@DateEnd)/14
				 WHEN 52 THEN DATEDIFF(dd,@DateStart,@DateEnd)/7
			END
END

DECLARE @FPD datetime --First Payment Date
	SET @FPD = 
		CASE @FreqPerYear
			 WHEN 12 THEN DATEADD(mm,@FNP,@DateStart)
			 WHEN 24 THEN DATEADD(dd,15*(@FNP%2),DATEADD(mm,@FNP/2,@DateStart))
			 WHEN 26 THEN DATEADD(wk,2*@FNP,@DateStart)
			 WHEN 52 THEN DATEADD(wk,@FNP,@DateStart)
		END

INSERT INTO @T VALUES(@FNP,DATEDIFF(dd,@FPD,@DateEnd))
RETURN

END
